/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 */
export function handleTree(
  data,
  id = 'id',
  parentId = 'parentId',
  children = 'children'
) {
  const childrenListMap = new Map()
  const nodeIds = new Set()
  const tree = []

  for (const d of data) {
    const parent = d[parentId]
    if (!childrenListMap.has(parent)) {
      childrenListMap.set(parent, [])
    }
    childrenListMap.get(parent).push(d)
    nodeIds.add(d[id])
  }

  for (const d of data) {
    if (!nodeIds.has(d[parentId])) {
      tree.push(d)
    }
  }

  // Populate children recursively
  const assignChildren = (node) => {
    node[children] = childrenListMap.get(node[id]) || []
    for (const child of node[children]) {
      assignChildren(child)
    }
  }

  for (const root of tree) {
    assignChildren(root)
  }

  return tree
}

/**
 * 构造Url参数
 * @param {*} params 参数
 * @returns string
 */

export function buildQueryString(params) {
  const queryString = Object.keys(params)
    .map(
      (key) => encodeURIComponent(key) + '=' + encodeURIComponent(params[key])
    )
    .join('&')
  return queryString
}
